package com.anrongtec.zcpt.logo;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.authentication.AuthorizeLoginObserver;
import com.anrongtec.zcpt.authentication.AuthorizeReceiver;
import com.anrongtec.zcpt.authentication.BillOperation;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.base.DDApp;
import com.anrongtec.zcpt.callback.StoreStringCallBack;
import com.anrongtec.zcpt.callback.StringDialogCallback;
import com.anrongtec.zcpt.constant.Constant;
import com.anrongtec.zcpt.constant.PreferenceKey;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.ShuJuURL;
import com.anrongtec.zcpt.interfaces.URLConstants;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.interfaces.theInferfaces.HttpInterfaces;
import com.anrongtec.zcpt.module.LoginIP;
import com.anrongtec.zcpt.module.LoginUserInfo;
import com.anrongtec.zcpt.module.Staff;
import com.anrongtec.zcpt.module.User;
import com.anrongtec.zcpt.module.XdjaBill;
import com.anrongtec.zcpt.openapi.manager.IAuthCallBack;
import com.anrongtec.zcpt.openapi.manager.OperationCallBack;
import com.anrongtec.zcpt.openapi.manager.UAManager;
import com.anrongtec.zcpt.openapi.model.AccessTokenInfo;
import com.anrongtec.zcpt.util.GsonUtil;
import com.anrongtec.zcpt.util.JsonParse;
import com.anrongtec.zcpt.util.LogUtil;
import com.anrongtec.zcpt.util.RSAUtils;
import com.anrongtec.zcpt.util.Util;
import com.anrongtec.zcpt.view.KeyboardView;
import com.art.base.util.AppCacheUtils;
import com.art.base.util.DeviceFactory;
import com.art.base.util.DialogUtil;
import com.art.base.util.FileUtils;
import com.art.base.util.JSONHelper;
import com.art.base.util.PreferenceUtils;
import com.art.base.util.ToastShow;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;



/**
 * @author dongtianhao
 * @ClassName: LoginActivity
 * @Description: 登录页面
 * @date 2016年6月26日 下午9:11:26
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener, OnCheckedChangeListener, TextWatcher {
    /**
     * setting
     */
    private EditText et_ip, et_port, et_push_ip, et_push_port;
    private View settingView;
    private Dialog settingDialog;

    /**
     * 登录方式
     */
    private static final int LOGIN_TYPE_CODE = 1, LOGIN_TYPE_SFZH = 2, LOGIN_TYPE_OAUTH = 3;// 3
    // 为广西登录方式

    private int currentType = 1;
    private String token;

    private RadioGroup rgroup;
    private RadioButton rb_code, rb_sfzh;
    private ImageView iv_user_clear, iv_psw_clear, iv_show_pw, iv_setting;
    private EditText et_user, et_psw;
    private String username, password;
    private boolean isShowed = false;// 默认不显示密码

    private LinearLayout ll;

    private KeyboardView keyboard_view;

    private static final String CACHE_USER = "user";

    private static final int SHOW_LOGIN_VIEW = 1;
    private static final int SHOW_LOGIN_CONFIG=5;
    private static final long SHOW_DELAY_TIME = 500;
    private User jsonData;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_LOGIN_VIEW:
                    ll.setAnimation(anim);
                    ll.setVisibility(View.VISIBLE);
                    keyboard_view.setInputView(et_user, LoginActivity.this);
                    break;
                case SHOW_LOGIN_CONFIG:
                    jsonData= (User) msg.obj;
//                    if(jsonData!=null){
//                        saveloginInfo();
//                    }
                    getConfig();
                    break;

            }
        }
    };
    private Animation anim;

    /**
     * 缓存警号, 缓存身份证号
     */
    private HashMap<String, User> cacheUserCode, cacheUserSfzh;

    private String fId;

    private Staff staff;
    private boolean isBind;// 是否绑定服务

    private ProgressDialog proDialog;
    private String mPackageName;
    AuthorizeReceiver authorizeReceiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleShow(false);
        setContentView(R.layout.activity_login);

        Intent intent = getIntent();
        if (intent != null && intent.getStringExtra("IntentData") != null) {
            finish();
        }

        initViews();
        initEvents();
        initUserCache();

//        //获取票据
//        authorizeReceiver = new AuthorizeReceiver();
//        AuthorizeReceiver.registerObserver(new Oberver());
//        //接收票据广播
//        IntentFilter filter = new IntentFilter();
//        filter.addAction("com.anrongtec.zcpt");
//        //注册广播接收
//        registerReceiver(authorizeReceiver,filter);
//
//        String billInfoByCurosr = BillOperation.getBillInfoByCurosr(LoginActivity.this);
//        if(!TextUtils.isEmpty(billInfoByCurosr)){
//            uaslogin(billInfoByCurosr);
//        }
/*
        CheckNewVersionManager.getInstance().checkVersion(this, false);
        //广西统一认证
//        OAuthLogin();
//        startService(new Intent(this, GetPushInfoService.class));*/
    }

//    String username ="111116";

    String json = "{\n" +
            "\t\"flag\": \"验证结果\",\n" +
            "\t\"message\": \"提示信息\",\n" +
            "\t\"id\": \"暂不使用\",\n" +
            "\t\"userInfo\": {\n" +
            "\t\t\"id\": \"1\",\n" +
            "\t\t\"name\": \"姓名\",\n" +
            "\t\t\"sex\": \"性别\",\n" +
            "\t\t\"code\": \"111116\",\n" +
            "\t\t\"depcode\": \"单位编码\",\n" +
            "\t\t\"depid\": \"单位ID\",\n" +
            "\t\t\"identifier\": \"身份证号\",\n" +
            "\t\t\"mobile\": \"手机号\",\n" +
            "\t\t\"police\": \"警种\",\n" +
            "\t\t\"position\": \"职级\",\n" +
            "\t\t\"effectivedate\": \"票据有效期\",\n" +
            "\t\t\"limits\": [\"终端访问权限\", \"终端访问权限\"]\n" +
            "\t}\n" +
            "}";
    private  void uaslogin(String bill){
        try {
            HttpInterfaces.getXdjaBillInfo(ShuJuURL.GET_BILL, bill, new com.anrongtec.zcpt.interfaces.theInferfaces.callback.StringDialogCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    XdjaBill xdjaBill = JsonParse.parseJsonWithGson(s, XdjaBill.class);
                    username = xdjaBill.getUserInfo().getCode();
                    String password ="111111";

                    RSAUtils rsa = RSAUtils.create();
                    String encodeUserName = rsa.encodeByPublicKey(username, RSAUtils.pubKey);//
                    String encodePassWd = rsa.encodeByPublicKey(password, RSAUtils.pubKey);
                    Login(encodeUserName, encodePassWd);
                }
                @Override
                public void onError(Call call, Response response, Exception e) {
                    //super.onError(call, response, e);
                    XdjaBill xdjaBill = JsonParse.parseJsonWithGson(json, XdjaBill.class);
                    username = xdjaBill.getUserInfo().getCode();
                    String password ="111111";

                    RSAUtils rsa = RSAUtils.create();
                    String encodeUserName = rsa.encodeByPublicKey(username, RSAUtils.pubKey);//
                    String encodePassWd = rsa.encodeByPublicKey(password, RSAUtils.pubKey);
                    Login(encodeUserName, encodePassWd);
                }
            });

        }catch (Exception e){
            e.printStackTrace();
        }

    }
     class  Oberver implements AuthorizeLoginObserver {

         @Override
         public void loginSuccess() {
             String billInfoByCurosr = null;
             try {
                 billInfoByCurosr = BillOperation.getBillInfoByCurosr(LoginActivity.this);
                 if(!TextUtils.isEmpty(billInfoByCurosr)){
                     uaslogin(billInfoByCurosr);
                 }
             } catch (Exception e) {
                 e.printStackTrace();
                 ToastShow.shortMessage(e.getMessage());
             }


         }
     }
    @Override
    protected void onResume() {
//		Login("452201198503231249");
        super.onResume();
    }

    /***
     * 广西统一认证
     */
    private void OAuthLogin() {
        UAManager.getInstance().init(getApplicationContext(), "b1dfe9523fa21da916acc8cc95d7f8ad");

        proDialog = DialogUtil.createLoadingDialog(this, "正在登录...");
        mPackageName = Util.getPackageName(this);
        UAManager.getInstance().authLogin(this, mPackageName, new IAuthCallBack() {

            private String accessToken;

            @Override
            public void onSuccess(AccessTokenInfo info) {
                proDialog.setMessage("认证成功");
                accessToken = info.getAccessToken();
                PreferenceUtils preUtils = PreferenceUtils.getInstance(getApplicationContext());
                preUtils.save(Constant.NETTYPE, info.getNetType());
                DDApp.dApp.getBaseInfo().put("netType", info.getNetType());
                getStaffInfo(accessToken);
            }

            @Override
            public void onProgress(final String msg) {
                Util.post(LoginActivity.this, new Runnable() {
                    public void run() {
                        proDialog.setMessage(msg);// 000001 888888
                    }
                });
            }

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onError(int code, String msg) {
                proDialog.cancel();
                // 已经销毁了就算了
                if (LoginActivity.this.isDestroyed()) {
                    return;
                }
                DialogUtil.createAlertDialogSingel(LoginActivity.this, "温馨提示", msg, new Dialog.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
            }


        });
    }

    /**
     * 获取用户信息
     *
     * @param accessToken
     */
    private void getStaffInfo(String accessToken) {
        UAManager.getInstance().getStaffInfo(accessToken, new OperationCallBack() {

            @Override
            public void onSuccess(String json) {
                Staff staff = JSONHelper.parseInfoFromJson(json, Staff.class);
                if (staff == null) {
                    if (proDialog != null && proDialog.isShowing()) {
                        proDialog.cancel();
                    }
                    DialogUtil.createAlertDialog(LoginActivity.this, "温馨提示", "获取用户信息失败");
                    return;
                }

                Util.post(LoginActivity.this, new Runnable() {

                    @Override
                    public void run() {
                        if (proDialog != null && proDialog.isShowing()) {
                            proDialog.setMessage("正在登录...");
                        }
                    }
                });
                Login(staff.getStaffIdno());

            }

            @Override
            public void onError(int code, String msg) {
                if (proDialog.isShowing()) {
                    proDialog.cancel();
                }
                DialogUtil.createAlertDialog(LoginActivity.this, "温馨提示", msg);

            }
        });

    }

    /***
     *
     */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        LogUtil.d(data.getStringExtra());
//        UAManager.getInstance().decodeResult(requestCode, resultCode, data);
        // if (TextUtils.isEmpty(json)) {
        // if (proDialog != null && proDialog.isShowing()) {
        // proDialog.cancel();
        // DialogUtil.createAlertDialogSingel(LoginActivity.this, "温馨提示",
        // "认证取消", new Dialog.OnClickListener() {
        //
        // @Override
        // public void onClick(DialogInterface dialog, int which) {
        // finish();
        // }
        // });
        // }
        // }
    }

    /**
     * 初始化用户缓存信息
     */
    private void initUserCache() {
        cacheUserSfzh = (HashMap<String, User>) AppCacheUtils.getInstance(this, CACHE_USER).getObject(CACHE_USER);
        // 缓存
        AppCacheUtils.getInstance(this, CACHE_USER).put(CACHE_USER, cacheUserSfzh);
    }

    /**
     *
     * 显示登录界面
     */
    // private void showLoginView() {
    // handler.sendEmptyMessageDelayed(SHOW_LOGIN_VIEW, SHOW_DELAY_TIME);
    // }
    @Override
    protected void initViews() {
        rgroup = (RadioGroup) findViewById(R.id.radio_group_login);
        rb_code = (RadioButton) findViewById(R.id.radio_button_login_code);
        rb_sfzh = (RadioButton) findViewById(R.id.radio_button_login_sfzh);

        et_user = (EditText) findViewById(R.id.et_login_user);
        et_psw = (EditText) findViewById(R.id.et_login_password);
        iv_user_clear = (ImageView) findViewById(R.id.iv_login_user_clear);
        iv_psw_clear = (ImageView) findViewById(R.id.iv_login_password_clear);
        refresh();
        iv_show_pw = (ImageView) findViewById(R.id.iv_login_show_password);//密码可见

        keyboard_view = (KeyboardView) findViewById(R.id.keyboardView);//键盘
        // true是身份证输入法, false是警号输入法
        keyboard_view.setIsIdno(false);

        ll = (LinearLayout) findViewById(R.id.ll_login);
        anim = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);

        //设置按钮
        iv_setting = (ImageView) findViewById(R.id.iv_login_setting);
    }

    @Override
    protected void initEvents() {
        findViewById(R.id.btn_login_login).setOnClickListener(this);
        findViewById(R.id.iv_login_close).setOnClickListener(this);

        rgroup.setOnCheckedChangeListener(this);
        et_user.addTextChangedListener(this);
        et_psw.addTextChangedListener(this);

        iv_user_clear.setOnClickListener(this);
        iv_psw_clear.setOnClickListener(this);

        iv_show_pw.setOnClickListener(this);
        iv_setting.setOnClickListener(this);

    }

    /**
     * 广西用MDM返回的用户信息登录，
     *
     * @param idno
     */
    private void Login(final String idno) {
        RSAUtils rsa = RSAUtils.create();
        String encodeIdno = rsa.encodeByPublicKey(idno, RSAUtils.pubKey);
        currentType = 3;
        // 初始化baseinfo
        DDApp.dApp.initBaseInfo();
        // 组装登录请求的json
        final String json = GsonUtil.toLoginJson(encodeIdno);
        HttpUtil.post(json, new StoreStringCallBack(this) {
            @Override
            public void onResponse(boolean arg0, String arg1, Request arg2, Response arg3) {
                super.onResponse(arg0, arg1, arg2, arg3);
                LogUtil.e("用户信息" + arg1);
                JsonDataRestult<User> jsonData = GsonUtil.decode(arg1, new TypeToken<JsonDataRestult<User>>() {
                }.getType());
                if (URLConstants.RetCode.SUCCESS.equals(jsonData.getRetCode())) {
                    if (jsonData.getData() != null) {
                        String accountId = jsonData.getData().getAccountId();
                        // TODO 上传登录操作
                        // WLData.getInstance().reportLogin(accountId,
                        // Events.LOGIN);
                        // 保存当前用户的用户名
                        PreferenceUtils.getInstance(getApplicationContext()).save(PreferenceKey.ACCOUNT_ID, idno);
                        PreferenceUtils.getInstance(getApplicationContext()).save(PreferenceKey.TIMEOUT, Integer.parseInt(jsonData.getData().getTimeout()));
                        PreferenceUtils.getInstance(getApplicationContext()).save(PreferenceKey.LASTREQUEST, System.currentTimeMillis());
                        DDApp.dApp.setCurrentUser(jsonData.getData());
                        if (proDialog != null && proDialog.isShowing()) {
                            proDialog.cancel();
                        }
                        startActivity(MainActivity.class);
                        finish();
                        return;
                    } else {
                        if (proDialog != null && proDialog.isShowing()) {
                            proDialog.cancel();
                        }
                        DialogUtil.createAlertDialogSingel(LoginActivity.this, "温馨提示", "用户信息验证失败",
                                new Dialog.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        finish();
                                    }
                                });
                    }
                } else {
                    if (proDialog != null && proDialog.isShowing()) {
                        proDialog.cancel();
                    }
                    DialogUtil.createAlertDialogSingel(LoginActivity.this, "温馨提示", jsonData.getRetMsg(),
                            new Dialog.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            });
                }
            }

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onError(boolean isFromCache, Call call, Response response, Exception e) {
                if (proDialog != null && proDialog.isShowing()) {
                    proDialog.cancel();
                }
                if (response == null) {
                    ToastShow.shortMessage(getString(R.string.alert_failed_connect));
                }
                if (LoginActivity.this.isDestroyed() || LoginActivity.this.isFinishing()) {
                    return;
                }
                try {
                    DialogUtil.createAlertDialogSingel(LoginActivity.this, "温馨提示", "用户信息验证失败",
                            new Dialog.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            });
                } catch (Exception e1) {
                    e1.printStackTrace();
                }

                super.onError(isFromCache, call, response, e);
                e.printStackTrace();
            }
        });

    }

    /**
     * 登录
     */
    private void Login() {
        RSAUtils rsa = RSAUtils.create();
        String encodeUserName = rsa.encodeByPublicKey(username, RSAUtils.pubKey);//
        String encodePassWd = rsa.encodeByPublicKey(password, RSAUtils.pubKey);
        Login(encodeUserName, encodePassWd);

//        String decodeusername = rsa.decodeByPublicKey(encodeUserName,RSAUtils.pubKey);
//        String decodepsd = rsa.decodeByPublicKey(encodePassWd,RSAUtils.pubKey);

       // LogUtil.e("加密  username : "+encodeUserName+"解密 username: " +rsa.decodeByPublicKey(encodeUserName,RSAUtils.pubKey));

    }

    /**
     * 登录
     *
     * @param encodeUserName 账号
     * @param encodePassWd   密码
     */
    private void Login(String encodeUserName, String encodePassWd) {
        // 初始化baseinfo
        DDApp.dApp.initBaseInfo();
        String number = DeviceFactory.getInstance(this).getPhoneNumber();

        String secretid = DeviceFactory.getInstance(this).getCardId();
         Log.e("number",number+"");
        // 组装登录请求的json
        final String json = GsonUtil.toLoginJson(encodeUserName, encodePassWd,number,secretid,
                currentType);
        LogUtil.e(json);

        HttpUtil.post(json, new StringDialogCallback(this, "正在登录...") {

            @Override
            public void onResponse(boolean arg0, String arg1, Request arg2, Response
                    arg3) {
                LogUtil.e("用户信息" + arg1);
                // JsonDataRestult<User> jsonData = GsonUtil.decode(arg1,
                // User.class);
                JsonDataRestult<User> jsonData = GsonUtil.decode(arg1, new
                        TypeToken<JsonDataRestult<User>>() {
                        }.getType());
                if (URLConstants.RetCode.SUCCESS.equals(jsonData.getRetCode())) {

                    if (jsonData.getData() != null) {

                        ///change by lina
                       /* String accountId = jsonData.getData().getAccountId();
                        // TODO 上传登录操作
//                      WLData.getInstance().reportLogin(accountId, Events.LOGIN);
                        // 保存当前用户的用户名
                        PreferenceUtils.getInstance(LoginActivity.this).save(PreferenceKey.ACCOUNT_ID,
                                accountId);

                          //保存信息
                        DDApp.dApp.setCurrentUser(jsonData.getData());

                        startActivity(MainActivity.class);
                        finish();*/
                        handler.sendMessage(handler.obtainMessage(SHOW_LOGIN_CONFIG,jsonData.getData()));
                    } else {
                        handler.sendEmptyMessage(SHOW_LOGIN_VIEW);
                    }
                } else {
                    ToastShow.shortMessage(jsonData.getRetMsg());

                    handler.sendEmptyMessage(SHOW_LOGIN_VIEW);
                }
            }
            @Override
            public void onError(boolean isFromCache, Call call, Response response,
								Exception e) {

                if (response == null) {
                    ToastShow.shortMessage(getString(R.string.alert_failed_connect));
                }
                handler.sendEmptyMessage(SHOW_LOGIN_VIEW);
                super.onError(isFromCache, call, response, e);
            }
        });
    }
    /**
     * 检查输入格式
     */
    private boolean checkLoginInfo() {
        username = et_user.getText().toString().trim();
        password = et_psw.getText().toString().trim();
        if (currentType == LOGIN_TYPE_CODE) {//输入方式  警号输入
            if (TextUtils.isEmpty(username)) {
                et_user.setError("警号不能为空");
                return false;
            }
            if (username.length() != 6) {
                et_user.setError("警号输入错误");
                return false;
            }
        }
        if (currentType == LOGIN_TYPE_SFZH) {//身份证输入
            if (TextUtils.isEmpty(username)) {
                et_user.setError("身份证号不能为空");
                return false;
            }
            if (username.length() != 18) {
                et_user.setError("身份证号输入错误");
                return false;
            }
        }
        if (TextUtils.isEmpty(password)) {
            et_psw.setError("密码不能为空");
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_login_login:
                if (checkLoginInfo()) {//检验登录方式(1警号 2 身份证)
                    Login();
                }
                break;

            case R.id.iv_login_close:
                finish();
                break;

            case R.id.iv_login_user_clear:
                et_user.setText("");
                break;
            case R.id.iv_login_password_clear:
                et_psw.setText("");
                break;

            case R.id.iv_login_show_password:
                if (isShowed) {
                    iv_show_pw.setImageResource(R.drawable.eye_close);
                    et_psw.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                    isShowed = false;
                } else {
                    iv_show_pw.setImageResource(R.drawable.eye_open);
                    et_psw.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD | InputType.TYPE_CLASS_TEXT);
                    isShowed = true;
                }
                et_psw.setSelection(et_psw.getText().toString().length());
                break;
            case R.id.iv_login_setting:
                showSetting();
                break;

        }
    }

    /**
     * radiobutton监听
     */
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.radio_button_login_code:
                currentType = LOGIN_TYPE_CODE;
                et_user.setHint("警号");
                keyboard_view.setIsIdno(false);
                break;
            case R.id.radio_button_login_sfzh:
                currentType = LOGIN_TYPE_SFZH;
                et_user.setHint("身份证号");
                keyboard_view.setIsIdno(true);
                break;
            default:
                break;
        }
        et_user.setError(null);
    }
    /**
     * 输入监听
     */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        et_user.setError(null);
        refresh();
    }

    @Override
    public void afterTextChanged(Editable s) {
    }
    /**
     * 刷新
     */
    private void refresh() {
        username = et_user.getText().toString();
        if (username.length() != 0) {
            iv_user_clear.setVisibility(View.VISIBLE);
        } else {
            iv_user_clear.setVisibility(View.GONE);
        }
        password = et_psw.getText().toString();
        if (password.length() != 0) {
            iv_psw_clear.setVisibility(View.VISIBLE);
        } else {
            iv_psw_clear.setVisibility(View.GONE);
        }
    }

    @SuppressLint("NewApi")
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!event.isFromSource(et_user.getId()) && event.getAction() == MotionEvent.ACTION_DOWN) {
            keyboard_view.setVisibility(View.GONE);
        }
        return super.onTouchEvent(event);
    }

    private String idno;

    @Override
    protected void onDestroy() {
//        UAManager.getInstance().cancelAuth();
//        unregisterReceiver(authorizeReceiver);
        super.onDestroy();
    }

    /**
     * 显示设置对话框
     */
    private void showSetting() {
        settingView = LayoutInflater.from(this).inflate(R.layout.dialog_login_setting, null);
        et_ip = (EditText) settingView.findViewById(R.id.et_ip);
        et_port = (EditText) settingView.findViewById(R.id.et_port);
        et_ip.setText(PreferenceUtils.getInstance().getString(ShuJuURL.IP, ShuJuURL.DEFAULT_IP));
        et_port.setText(PreferenceUtils.getInstance().getInt(ShuJuURL.PORT, ShuJuURL.DEFAULT_PORT) + "");

        et_push_ip = (EditText) settingView.findViewById(R.id.et_push_ip);
        et_push_port = (EditText) settingView.findViewById(R.id.et_push_port);
        et_push_ip.setText(PreferenceUtils.getInstance().getString(ShuJuURL.PUSH_IP, ShuJuURL.DEFAULT_PUSH_IP));
        et_push_port.setText(PreferenceUtils.getInstance().getInt(ShuJuURL.PUSH_PORT, ShuJuURL.DEFAULT_PUSH_PORT) + "");

        settingDialog = DialogUtil.createViewDialog(this, "设置", R.drawable.icon_tab04_setting, settingView, true, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                PreferenceUtils.getInstance().save(ShuJuURL.IP, et_ip.getText().toString());
                PreferenceUtils.getInstance().save(ShuJuURL.PORT, Integer.parseInt(et_port.getText().toString()));
                PreferenceUtils.getInstance().save(ShuJuURL.PUSH_IP, et_push_ip.getText().toString());
                PreferenceUtils.getInstance().save(ShuJuURL.PUSH_PORT, Integer.parseInt(et_push_port.getText().toString()));
            }
        }, true, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });

    }

    /*获取分离app 需要的ip*/
    private void getConfig(){
        HttpInterfaces.getConfig(ShuJuURL.GET_CONFIG+"code="+username, new com.anrongtec.zcpt.interfaces.theInferfaces.callback.StringDialogCallback(this,"正在加载,稍后....") {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LoginIP loginIP = JsonParse.parseJsonWithGson(s, LoginIP.class);

                if(null!=loginIP){
                    initConfig(loginIP);
                }
                Log.e("result",s);
                Log.e("loginip",loginIP.getData().get(0).getUrl());
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);

                ToastShow.makeToast(LoginActivity.this,e.getMessage());
                finish();
                Log.e("ip_erro",e.getMessage());
            }
        });
    }
    String ip,webInfo,upLoad,pushIp,imgCom;
    String sessionkey;
    private void initConfig(LoginIP loginIP) {
        for(int i=0;i<loginIP.getData().size();i++){

            switch (loginIP.getData().get(i).getName()){
                case "jwt":
                    ip = loginIP.getData().get(i).getUrl();
                    Log.e("ip=======" , ip);
                    break;
                case "static":
                    webInfo = loginIP.getData().get(i).getUrl();
                    Log.e("static=======" , webInfo);
                    break;
                case "push":
                    pushIp = loginIP.getData().get(i).getUrl();
                    Log.e("push=======" , pushIp);
                    break;
                case "upload":
                    upLoad = loginIP.getData().get(i).getUrl();
                    Log.e("upload=======" , upLoad);
                    break;
                case "th_imgcmp":
                    imgCom = loginIP.getData().get(i).getUrl();
                    Log.e("th_imgcmp=======" , imgCom);
                default:
                    break;
            }

        }
        getUserInfos();


    }

    private void getUserInfos() {
        //保存sessionkey
        // //add by lina  保存登录相关信息
        String imei = DeviceFactory.prefs.getString("prefs_device_id","");
        String imsi = DeviceFactory.prefs.getString("prefs_imsi_code","");
        String uuid = DeviceFactory.prefs.getString("prefs_device_uuid","");
        sessionkey = imei+imsi+uuid;
        HttpInterfaces.getSessionInfo(ShuJuURL.GET_INFO_BY_SEESIONKEY, sessionkey, new com.anrongtec.zcpt.interfaces.theInferfaces.callback.StringDialogCallback(LoginActivity.this,"......") {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if(!TextUtils.isEmpty(s)){
                    //保存用户的其他信息
                    saveloginInfo(s);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {

                super.onError(call, response, e);
                ToastShow.makeToast(LoginActivity.this,e.getMessage());
                finish();
            }
        });

    }

    /**
     * 保存用户信息
     * @param userinfo
     */
    private void saveloginInfo(String userinfo) {
        String accountId = jsonData.getAccountId();//当前的用户名
        // 保存当前用户的用户名
        PreferenceUtils.getInstance(LoginActivity.this).save(PreferenceKey.ACCOUNT_ID,
                accountId);
        DDApp.dApp.setCurrentUser(jsonData);
        LoginUserInfo loginUserInfo = JsonParse.parseJsonWithGson(userinfo, LoginUserInfo.class);

        Map<String,String> map = new HashMap<>();
        map.put("username",username);//警号
        map.put("password",password);
        map.put("ip",ip);
        map.put("pushIp",pushIp);
        map.put("webInfo",webInfo);
        map.put("upLoadIp",upLoad);
        map.put("imagCom",imgCom);
        map.put("dwdm",loginUserInfo.getOrganizationId());

        String json = GsonUtil.toJson(map);
        Log.e("jsonmap",json);

        //保存用户信息
        FileUtils.saveFile(userinfo,"userInfo.txt");

        FileUtils.saveFile(json,"loginInfo.txt");
        FileUtils.saveFile(sessionkey,"sesionkey.txt");

        //通过sessionkey 获取当前人员登录信息
        //===========================end====
        startActivity(MainActivity.class);
        finish();
    }

}
